use bevy::prelude::MouseButton;
use rusty_engine::game::Engine;
use crate::game_state::{GameScene, GameState};
use crate::scenes::switch_scene;

// 按钮尺寸
pub const BUTTON_WIDTH: f32 = 465.0;
pub const BUTTON_HEIGHT: f32 = 200.0;

// 检测鼠标是否在按钮内
pub fn in_button(engine: &mut Engine, key : &str) -> bool{
    if let Some(mouse_pos) = engine.mouse_state.location() {
        // 获取按钮精灵
        if let Some(button) = engine.sprites.get(key) {
            let half_width = button.scale * BUTTON_WIDTH / 2.0;
            let half_height = button.scale * BUTTON_HEIGHT / 2.0;

            let button_left = button.translation.x - half_width;
            let button_right = button.translation.x + half_width;
            let button_top = button.translation.y + half_height;
            let button_bottom = button.translation.y - half_height;

            // 检查鼠标是否在按钮区域内
            if mouse_pos.x >= button_left && mouse_pos.x <= button_right && mouse_pos.y >= button_bottom && mouse_pos.y <= button_top {
                return true;
            }
        }
    }
    false
}

// 悬停检测
pub fn hover_check(engine: &mut Engine, key : &str) {
    if in_button(engine, key) {
        // 添加悬浮反馈效果
        if let Some(button) = engine.sprites.get_mut(key) {
            button.scale = 0.675; // 按钮缩小效果
        }
    }
}

// 点击检测
pub fn click_check(engine: &mut Engine, game_state: &mut GameState, key : &str) -> bool{
    // 检测是否发生点击
    let mut flag = false;
    if engine.mouse_state.just_pressed(MouseButton::Left) {
        if in_button(engine, key) {
            // 执行场景切换逻辑
            if key == "start_single_button" {
                switch_scene(game_state, GameScene::SingleGame);
                flag = true;
            } else if key == "start_double_button" {
                switch_scene(game_state, GameScene::DoubleGame);
                flag = true;
            } else if key == "restart_button" {
                flag = true;
            } else if key == "menu_button" {
                switch_scene(game_state, GameScene::MainMenu);
                flag = true;
            }

            // 添加悬浮反馈效果
            if let Some(button) = engine.sprites.get_mut(key) {
                button.scale = 0.675; // 按钮缩小效果
            }
        }
    }
    flag
}
